package com.dys.testjdk11;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;

/**
 * @className: com.dys.testjdk11.HttpClientTest
 * @description: com.dys.testjdk11
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/09/04 下午11:30
 */
public class HttpClientTest {

    /**
     * 对WebSocket和HTTP2的支持
     *
     * @throws IOException
     * @throws InterruptedException
     */
    private static void testSynchronization() throws IOException, InterruptedException {
        // HttpClient 替换原有的HttpUrlConnection  同步方式
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder(URI.create("http://127.0.0.1:8080/demo")).build();
        HttpResponse.BodyHandler<String> respnoseBodyHandler = HttpResponse.BodyHandlers.ofString();
        HttpResponse<String> response = client.send(request, respnoseBodyHandler);
        String body = response.body();
        System.out.println(body);
    }

    /**
     * 异步
     */
    public static void testAsynchronous() {
        // HttpClient 替换原有的HttpUrlConnection  异步方式
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder(URI.create("http://127.0.0.1:8080/demo")).build();
        HttpResponse.BodyHandler<String> respnoseBodyHandler = HttpResponse.BodyHandlers.ofString();
        CompletableFuture<HttpResponse<String>> sendAsync = client.sendAsync(request, respnoseBodyHandler);
        sendAsync.thenApply(t -> t.body()).thenAccept(System.out::println);
    }
}
